<template>
  <div class="employees-container">
    <div class="app-container">

      <PageTools>
        <template #left>
          <span>总记录数：{{ total }}条</span>
        </template>
        <template #right>
          <el-button v-if="checkBtnAccess('POINT_EXCEL_IMPORT')" type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button v-if="checkBtnAccess('POINT_EXCEL_EXPORT')" type="danger" size="small" @click="handleDownLoad">excel导出</el-button>
          <el-button type="primary" size="small" @click="clickAdd">新增员工</el-button>
        </template>
      </PageTools>

      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" :index="indexMethod" sortable="" width="100" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template #default="{row}">
              <img v-imgerror="erroImg" class="staff" :src="row.staffPhoto || defaultImg" alt="" @click="show2CodeDialog(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" :formatter="formatFn" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry|formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button :disabled="!checkBtnAccess('POINT_USER_EDIT')" type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="clickAssignRole(row.id)">角色</el-button>
              <el-button :disabled="!checkBtnAccess('POINT_USER_DELETE')" type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 2, 3, 4, 5,6,7,8,9,10,15,20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <!-- 添加员工 -->
      <AddEmployee
        :show-dialog="isShow"
        @close-dialog="closeDialogFn"
        @addEmployee="getEmployee"
      />
      <!-- 二维码对话框 -->
      <el-dialog title="二维码预览" :visible="isShow2Code" @close="isShow2Code=false">
        <!-- 用于绘制复杂的二维码 作为二维码的容器 -->
        <div style="text-align:center">
          <canvas ref="myCanvas">二维码</canvas>
        </div>
      </el-dialog>

      <!-- 分配角色的对话框 -->
      <AssignRole
        :show-role-dialog.sync="showRoleDialog"
        :user-id="userId"
      />

    </div>
  </div>
</template>

<script>
import check from '@/mixins/check'
import AssignRole from './components/AssignRole.vue'
import obj from '@/constant/employees'
import AddEmployee from './components/AddEmployee.vue'
import dayjs from 'dayjs'
import erroImg from '@/assets/common/bigUserHeader.png'
import QrCode from 'qrcode'
// QrCode.toCanvs(canvas容器，信息='www。Baidu。com')=>得到二维码
// HTML5 画布标签canvas
import { reqDelEmployee, reqGetEmployeeList } from '@/api/employees'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  mixins: [check],
  data() {
    return {
      list: [],
      page: 1,
      size: 5,
      total: 0,
      isShow: false,
      defaultImg: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      erroImg: erroImg,
      isShow2Code: false,
      showRoleDialog: false,
      userId: ''

    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.size = val
      this.page = 1
      this.getEmployee()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.getEmployee()
    },

    async getEmployee() {
      this.loading = true
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.size)
      console.log(rows, total, 767676)
      this.list = rows
      this.total = total
      this.loading = false
    },

    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.size
    },

    formatFn(row, column, cellvalue, index) {
      // console.log(row, column, cellvalue, index)
      const { hireType } = obj
      const res = hireType.find(item => item.id === +cellvalue)
      return res ? res.value : '未知'
    },

    del(id) {
      this.$confirm('此操作将永久删除该员工，继续么？', '提示', { type: 'warning' })
        .then(async() => {
          const res = await reqDelEmployee(id)
          console.log(res, 112112)
          this.$message.success(res.message)
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.getEmployee()
        }).catch(() => {
          this.$message.success('已取消该操作')
        })
    },

    closeDialogFn() {
      this.isShow = false
    },

    async handleDownLoad() {
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      console.log(rows, 138138)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const dataArr = this.transArrayTo2wei(headersArr, headersRelations, rows)
      // multiHeader里面是一个二维数组，里面的一个元素是一行表头
      // const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 设置单元格的合并
      // const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // 动态导入
      import('@/vendor/Export2Excel').then(excle => {
        console.log(excle, 140)
        excle.export_json_to_excel({
          header: headersArr,
          data: dataArr,
          filename: '员工信息表',
          // filename: '复杂表头员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
          // multiHeader,
          // merges

        })
      })
    },

    // [ {} , {} ....]  =>  [ [] , [] ....]
    transArrayTo2wei(headersArr, headersRelations, rows) {
      // 认知1 小数组的个数 是由rows.length决定的
      // 认知2 小数组的内容个数，是由headersArr决定的
      const bigArr = []
      rows.forEach(item => {
        const smallArr = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let val = item[englishKey]
          // 处理时间格式
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            val = dayjs(val).format('YYYY年MM月DD日')
          }
          // 处理聘用形式
          if (englishKey === 'formOfEmployment') {
            const { hireType } = obj
            console.log(hireType, 11111)
            const res = hireType.find(v => v.id === +val)
            console.log(res, 183183)
            val = res ? res.value : '未知'
          }
          smallArr.push(val)
        })
        bigArr.push(smallArr)
      })
      console.log(bigArr, 172172)
      return bigArr
    },

    show2CodeDialog(imgUrl) {
      console.log(imgUrl)
      if (!imgUrl) return
      this.isShow2Code = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, imgUrl)
      })
    },

    clickAssignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },

    // checkBtnAccess(str) {
    //   // 有权限返回true;否则返回false
    //   const roles = this.$store.getters.roles
    //   // 新增的员工是没有角色, 没有权限的, 会有null的可能
    //   if (roles) {
    //     return roles.points.includes(str)
    //   } else {
    //     return false
    //   }
    // },
    clickAdd() {
      if (!this.checkBtnAccess('POINT_USER_ADD')) {
        this.$message.error('请联系管理员添加该权限')
        return
      }

      this.isShow = true
    }

  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
